<template>
  <page-header-wrapper>
    <a-card class="table-card menu-card-container">
      <gz-official-account-list v-model:value="officialAccount">
        <div class="menu-config-container">
          <div class="left">
            <div class="nav-bar">
              <div />
            </div>
            <div class="menu-list">
              <div v-for="(item, index) in menuConfig.button" class="menu-main">
                <div v-if="item.name" class="menu-item" :style="{ border: item.isClick? '1px solid #67c23a' : '1px solid #e8e8e8' }" @click="onButtonClick(item,index)">
                  {{ item.name }}
                </div>
                <div v-else-if="item.showAdd" class="menu-item" @click="addButton(item,index)">
                  + 
                </div>
                <div v-if="item.showSubButtons" class="menu-sub-list">
                  <template v-if="item.subButtons && item.subButtons.length > 0">
                    <div v-for="subItem in item.subButtons" class="menu-sub-item menu-main" :style="{ border: subItem.isClick? '1px solid #67c23a' : '1px solid #e8e8e8' }" @click="onSubButtonsClick(item,subItem)">{{ subItem.name }}</div>
                    <div v-if="item.subButtons.length < 5" class="menu-sub-item menu-main" @click="addSubButtons(item)">+</div>
                  </template>
                  <template v-else>
                    <div class="menu-sub-item menu-main" @click="addSubButtons(item)">+</div>
                  </template>
                </div>
              </div>
            </div>

            <!-- 保存并发布菜单 -->
            <div class="menu-footer">
              <a-button
                v-if="$access('ENT_MP_MENU_ADD')"
                type="primary"
                
                :loading="btnLoading"
                style="margin-top: 24px;"
                @click="saveAndPublish"
              >
                保存并发布
              </a-button>
            </div>
          </div>
          <div class="right">
            <div v-if="!currentButton">
              <!-- <div v-if="officialAccount?.wxOfficialChannel !== 'WxChat'">
                <p><strong>未开启自定义菜单</strong></p>
                <p>由于该公众号未托管，当前菜单配置已失效并停用。你可以前往机构公众号管理进行启用。</p>
              </div> -->
              <div>
                <p><strong>请选择菜单进行配置</strong></p>
              </div>
            </div>
            <a-form
              v-else
              ref="formRef"
              layout="vertical"
              :hideRequiredMark="true"
              :colon="false"
              labelAlign="left"
              :labelCol="{ span: 4 }"
              :wrapperCol="{ span: 20 }"
              style="margin-top: 30px; margin-left: 20px"
            >
              <a-row>
                <a-col v-if="$access('ENT_MP_MENU_DEL')" :span="24" style="text-align: right;">
                  <a-button danger type="primary" @click="deleteButton()"><delete-outlined />删除当前菜单</a-button>
                </a-col>
                <a-col :span="24">
                  <a-form-item label="菜单名称">
                    <a-input v-model:value="currentButton['name']" :maxlength="5" placeholder="请输入菜单名称" style="width: 50%;" />
                  </a-form-item>
                </a-col>
                <template v-if="!currentButton['subButtons'] || currentButton['subButtons'].length === 0">
                  <a-col :span="24">
                    <a-form-item label="菜单内容">
                      <a-select v-model:value="currentButton['type']" placeholder="请选择菜单内容" style="width: 50%;" @change="onTypeChange">
                        <a-select-option value="view">跳转网页</a-select-option>
                        <a-select-option value="miniprogram">跳转小程序</a-select-option>
                        <a-select-option value="click">点击回复</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <template v-if="currentButton['type'] === 'view'">
                    <a-col :span="24">
                      <a-form-item label="跳转链接">
                        <a-input v-model:value="currentButton['url']" placeholder="请输入跳转链接" style="width: 50%;" />
                      </a-form-item>
                    </a-col>
                  </template>
                  <template v-else-if="currentButton['type'] ==='miniprogram'">
                    <a-col :span="24">
                      <a-form-item label="小程序的appid">
                        <a-input v-model:value="currentButton['appid']" placeholder="请输入小程序的appid" style="width: 50%;" />
                      </a-form-item>
                    </a-col>
                    <a-col :span="24">
                      <a-form-item label="小程序的页面路径">
                        <a-input v-model:value="currentButton['pagepath']" placeholder="请输入小程序的页面路径" style="width: 50%;" />
                      </a-form-item>
                    </a-col>
                    <a-col :span="24">
                      <a-form-item label="备用网页">
                        <a-input v-model:value="currentButton['url']" placeholder="请输入备用网页" style="width: 50%;" />
                      </a-form-item>
                    </a-col>
                  </template>
                  <template v-else-if="currentButton['type'] === 'click'">
                    <a-col :span="24">
                      <a-form-item label="回复消息">
                        <gz-message-box ref="gzMessageBoxRef" v-model:repType="currentButton['repType']" v-model:value="currentButton['repValue']" style="width: 100%;" />
                      </a-form-item>
                    </a-col>
                  </template>
                </template>
              </a-row>
            </a-form>
          </div>
        </div>
      </gz-official-account-list>
    </a-card>
  </page-header-wrapper>
</template>

<script setup lang="ts">
import { ref, reactive, watch, getCurrentInstance } from 'vue'
import {$apiOfficialMenusSaveMenus,$apiOfficialMenusGetMenus,$apiOfficialMenusRemoveMenus} from '@/api/proxy/officialManage/menuManage/index'

const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
const gzMessageBoxRef = ref()

// 按钮loading
const btnLoading = ref(false)

// 当前点击的菜单按钮 即要进行配置的菜单项
const currentButton = ref(null) as any

// 菜单按钮配置
const menuConfig = reactive({
  button: []
} as any)

// 当前选中的公众号
const officialAccount = ref(null) as any
// 存储删除菜单的id
const menuId = ref('')

/**
 * 类型切换事件
 */
function onTypeChange(e){
  if(e === 'click'){
    if(!currentButton.value.repType){
      currentButton.value.repType = 'text'  // 默认为文本消息
    }
  }
}

/**
 * 菜单点击事件
 */
function onButtonClick(item: any, index) {
  menuId.value = item.menuId
  menuConfig.button.forEach(v => {
    v.isClick = false
    v.showSubButtons = false
  })
  clearSubButtonsClick()
  item.isClick = true
  item.showSubButtons = true
  currentButton.value = item
  
  if(!menuConfig.button[+index + 1] && index < 2){
    menuConfig.button.push({showAdd: true})
  }
}
/**
 * 新增菜单
 */
function addButton(item: any, index) {


  menuConfig.button.forEach(v => {
    v.isClick = false
    v.showSubButtons = false
  })

  clearSubButtonsClick()
  item.name = '新增菜单'
  item.isClick = true
  item.showSubButtons = true
  item.showAdd = false

  currentButton.value = item
  if(+index + 1 < 3){
    menuConfig.button.push({showAdd: true})
  }
}
/**
 * 清除子菜单被点击
 */
function clearSubButtonsClick() {
  menuConfig.button.forEach(button => {
    if(button.subButtons){
      button.subButtons.forEach(subButtons => {
        if(subButtons.isClick){
          subButtons.isClick = false
        }
      })
    }
  })
}
/**
 * 新增子菜单
 */
function addSubButtons(item: any) {
  if(!item.subButtons){
    item.subButtons = []
  }
  item.subButtons.forEach(v => {
    if(v.isClick){
      v.isClick = false
    }
  })
  item.isClick = false
  item.subButtons.push({
    name: '子菜单名称',
    isClick: true
  })
  currentButton.value = item.subButtons[item.subButtons.length - 1]
}
/**
 * 点击子按钮
 */
function onSubButtonsClick(item: any, subItem: any) {
  menuId.value = subItem.menuId
  item.isClick = false
  item.subButtons.forEach(v => {
    if(v.isClick){
      v.isClick = false
    }
  })
  subItem.isClick = true
  currentButton.value = subItem
}

/**
 * 删除当前菜单
 */
function deleteButton(){
  $infoBox.confirmDanger('确认删除？','确认删除当前菜单？',()=>{
    $apiOfficialMenusRemoveMenus({menuId:menuId.value,}).then(res=>{
      getMenuConfig()
    })
  })
  // $apiOfficialMenusRemoveMenus({menuId:menuId.value,})
  // $infoBox.confirmDanger('确认删除？','确认删除当前菜单？',()=>{
  //   const index = menuConfig.button.indexOf(currentButton.value)
  //   console.log(index,'index')
  //   if(index > -1){
  //     menuConfig.button.splice(index, 1)
  //     currentButton.value = null
  //   }else{
  //     for(let v of menuConfig.button){
  //       if(v.subButtons && v.subButtons.indexOf(currentButton.value) > -1){
  //         v.subButtons.splice(v.subButtons.indexOf(currentButton.value), 1)
  //         currentButton.value = null
  //         break
  //       }
  //     }
  //   }
  // })
}

/**
 * 获取菜单配置
 */
function getMenuConfig() {
  $apiOfficialMenusGetMenus({ appid: officialAccount.value.appId }).then((res: any) => {
    // 数据格式化
    if(!res|| res.button.length === 0){
      $infoBox.message.warn('公众号菜单未创建！')
      menuConfig.button = [{showAdd: true}]
      return
    }
    res.button.forEach(button => {
      button.isClick = false
      button.showSubButtons = false
      const { repContent, repMediaId, repUrl } = button
      
      button.repValue = { repContent, repMediaId, repUrl }
      if(button.subButtons && button.subButtons.length > 0){
        button.subButtons.forEach(subButtons => {
          const { repContent, repMediaId, repUrl } = subButtons
          subButtons.repValue = { repContent, repMediaId, repUrl }
        })
      }
    })
    menuConfig.button = res.button

  }).catch(()=>{
    menuConfig.button = [{showAdd: true}]
  })
}
watch(() => officialAccount.value, (newVal, oldVal) => {
  // if(!newVal) return
  getMenuConfig()
  currentButton.value = null
})

/**
 * 保存并发布菜单
 */
function saveAndPublish() {
  btnLoading.value = true
  menuConfig.appid = officialAccount.value.appId
  const reqData = JSON.parse(JSON.stringify(menuConfig))
  // 保存菜单数据处理
  reqData.button.forEach((button,index) => {
    if(button.subButtons?.length){  // 先过滤处理子菜单
      button.subButtons.forEach((subButtons,subIndex) => {
        const { name, type, url, appid, pagepath, repValue } = subButtons
        if(!name || !type){
          button.subButtons.splice(subIndex, 1)
          return
        }else{
          if(type === 'view'){
            if(!url){
              button.subButtons.splice(subIndex, 1)
              return
            }
          }
          if(type ==='miniprogram'){
            if(!appid || !pagepath || !url){
              button.subButtons.splice(subIndex, 1)
              return
            }
          }
          if(type === 'click'){
            const { repContent, repMediaId, repUrl } = repValue
            if(!repContent && !repMediaId && !repUrl){
              button.subButtons.splice(subIndex, 1)
              return
            }
            subButtons.key = `${index}-${subIndex}`
            // subButtons.key = 'rselfmenu_0_0'
            Object.assign(subButtons, subButtons.repValue)
          }
        }
      })
    }
    // 再处理父菜单
    const { name, type, url, appid, pagepath, repValue } = button
    if(!name){
      reqData.button.splice(index, 1)
      return
    }
    if(!type && (!button.subButtons || button.subButtons.length == 0)){
      reqData.button.splice(index, 1)
      return
    }
    if(type === 'view'){
      if(!url){
        reqData.button.splice(index, 1)
        return
      }
    }
    if(type ==='miniprogram'){
      if(!appid || !pagepath || !url){
        reqData.button.splice(index, 1)
        return
      }
    }
    if(type === 'click'){
      const { repContent, repMediaId, repUrl } = repValue
      if(!repContent && !repMediaId && !repUrl){
        reqData.button.splice(index, 1)
        return
      }
      // button.key = `${index}`
      button.key = 'rselfmenu_0_0'
      Object.assign(button, button.repValue)
    }
    if(button.subButtons?.length){
      // 过滤父菜单的属性
      reqData.button[index] = filterObj(button, 'name', 'officialAppId', 'officialMenuId', 'sort', 'createdUid', 'createdAt', 'subButtons')
    }
  })
  $apiOfficialMenusSaveMenus(reqData).then(res => {
    getMenuConfig()
    $infoBox.message.success('菜单保存成功')
  }).finally(() => {
    btnLoading.value = false
  })
}

/**
 * 对象属性过滤器
 * @param {Object} obj 要过滤的对象
 * @param  {Array} props 要保留的属性名
 * @returns {Object} 过滤后的对象
 */
function filterObj(obj, ...props) {
  if(!obj || typeof obj!== 'object'){
        return obj
    }
    let newObj = {}
    for(let key in obj){
        if(props.includes(key)){
            newObj[key] = obj[key]
        }
    }
    return newObj
}

</script>

<style lang="less" scoped>
  .menu-card-container{

    .inner{
      display: flex;
    }

    .menu-config-container{
      padding: 24px;
      box-sizing: border-box;
      border: 1px solid #e8e8e8;
      display: flex;
      gap: 24px;
      border-radius: 8px;

      .left{
        float: left;
        display: inline-block;
        width: 350px;
        height: 715px;
        background: url('https://demo.joolun.com/img/iphone_backImg.8f7788a1.png') no-repeat;
        background-size: 100% auto;
        padding: 518px 25px 88px;
        position: relative;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;

        .nav-bar{
          width: 300px;
          height: 64px;
          background: url('https://demo.joolun.com/img/menu_head.1c931282.png') no-repeat 0 0 / 100% 100%;
          position: relative;
          bottom: 426px;
          div{
            color: #fff;
            font-size: 14px;
            width: 100%;
            text-align: center;
            position: absolute;
            top: 33px;
            left: 0;
          }
        }
        .menu-list{
          background: transparent url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/f4d803b0-c221-47b3-93af-6f959419f6c5.png') no-repeat 0 0;
          padding-left: 43px;
          font-size: 12px;
          height: 44px;

          .menu-main{
            position: relative;
            float: left;
            display: inline-block;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            width: 85.5px;
            height: 44px;
            line-height: 44px;
            text-align: center;
            border: 1px solid #ebedee;
            background-color: #fff;
            cursor: pointer;
            
            .menu-item{
              height: 44px;
            }

            .menu-sub-list{
              position: absolute;
              bottom: 44px;
            }

            &::after{
              content: "";
              display: table;
              clear: both;
            }
          }
        }

        .menu-footer{
          border: none;
          cursor: initial;

          &:hover{
            background: initial;
          }
        }
      }

      .right{
        flex-grow: 1;
      }
    }
  }
</style>